#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "stdlib.h"
#include "string.h"
#include "sys/ioctl.h"
#include "sys/time.h"
#include "poll.h"
#include "sys/select.h"
#include "signal.h"

static int fd = 0;

static void sigio_signal_func(int num)
{
	int err;
	unsigned int keyvalue = 0;
	err = read(fd, &keyvalue, sizeof(keyvalue));

	if (err<0)
	{
		printf("err!!! err!!! \r\n");
	}
	else
	{
		printf("sigio signal! key value = %d \r\n", keyvalue);
		fflush(stdout);
	}
}

int main(int argc, char *argv[]){

	int ret;
	char flags;
	char *filename;


	if (argc != 2) {
		printf("Error Usage!\r\n");
		return -1;
	}
	
	filename = argv[1];
	fd = open(filename, O_RDWR);
	if(fd < 0) {
		printf("file %s open failed\r\n",filename);
		return -1;
	}

	signal(SIGIO, sigio_signal_func);

    fcntl(fd, F_SETOWN, getpid());
	flags = fcntl(fd, F_GETFL);
	fcntl(fd, F_SETFL, flags | FASYNC);



	while (1){
		sleep(2);
	}

	ret = close(fd);  // close文件
	if(ret <0){
		printf("file %s close failed \r\n",argv[1]);
		return -1;
	}

	return 0;
}
